package com.dz.client.controller;

import com.dz.client.pojo.UserProduct;
import com.dz.client.service.UserProductService;
import com.dz.server.pojo.Product;
import com.dz.server.pojo.User;
import com.dz.server.service.AtomicService;
import com.dz.server.service.ProductAtomicService;
import com.dz.server.service.ProductService;
import com.dz.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/client")
public class ClientProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserProductService userProductService;

    @RequestMapping("/toShowProduct{productId}")
    public String toShowProduct(@PathVariable("productId")Integer id, Model model){
        Product product = productService.getById(id);
        model.addAttribute("product",product);
        return "client/show-product";
    }
    //购买产品
    @RequestMapping("/buyProduct{productId}")
    public String buyProduct(@PathVariable("productId")Integer pid, HttpSession session,Model model){
        String username =(String) session.getAttribute("username");
        User user = userService.selectUserByName(username);
        List<Product> products = userProductService.getProductIds(user.getId());
        Product buyProduct = productService.getById(pid);
        if (products.contains(buyProduct)){
            model.addAttribute("msg","该产品已购买，请勿重复购买");
            model.addAttribute("product",buyProduct);
            return "client/show-product";
        }
        UserProduct userProduct = new UserProduct(user.getId(), pid);
        userProductService.save(userProduct);
        return "redirect:/toProductManage";
    }
}
